<template>
  <div class="chat-container">

    <!-- 添加清除历史按钮和导出/导入功能 -->
    <div class="chat-actions">
      <el-button type="primary" size="small" @click="exportChatHistory">
        导出聊天记录
      </el-button>
      <el-button type="success" size="small" @click="triggerImport">
        导入聊天记录
      </el-button>
      <el-button type="danger" size="small" @click="handleClearAllChatHistory">
        清除所有聊天记录
      </el-button>
      <input type="file" ref="fileInput" @change="importChatHistory" style="display: none;" accept=".json">
    </div>
    <!-- 聊天区域 -->
    <div class="chat-messages" ref="messagesRef">
      <!-- 消息列表 -->
      <template v-for="(message, index) in messages" :key="index">
        <!-- 用户消息 -->
        <div v-if="message.role === 'user'" class="message-item user-message">
          <div class="message-content">
            <div class="message-bubble">
              <p v-html="formatMessageContent(message.content)"></p>
            </div>
            <div class="message-time">
              <span>{{ formatTime(message.time) }}</span>
              <div class="message-actions">
                <el-icon @click="deleteMessage(index)"><Delete /></el-icon>
                <el-icon @click="copyMessage(message.content)"><CopyDocument /></el-icon>
              </div>
            </div>
          </div>
          <div class="avatar avataruser">
            <el-avatar :size="40" :src="userAvatar" />
          </div>
        </div>
        
        <!-- AI消息 -->
        <div v-else class="message-item ai-message">
          <div class="avatar">
            <el-avatar :size="40" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <p v-html="formatMessageContent(message.content)"></p>
              <div v-if="message.loading" class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
            <div class="message-time">
              <span>{{ formatTime(message.time) }}</span>
              <div class="message-actions">
                <el-icon @click="deleteMessage(index)"><Delete /></el-icon>
                <el-icon @click="copyMessage(message.content)"><CopyDocument /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
    
    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="1"
        :placeholder="'按Enter发送/Shift+Enter 换行'"
        resize="none"
        @keydown.enter="handleEnterKey"
        ref="inputRef"
        autosize
        :disabled="isLoading"
      />
      <div class="send-button-wrapper">
        <div class="send-button" @click="sendMessage" :class="{ disabled: !inputMessage.trim() || isLoading }">
          <el-icon><ArrowRight /></el-icon>
        </div>
      </div>
    </div>
    
    
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { Delete, CopyDocument, ArrowRight } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/user';
import { ElMessage } from 'element-plus';
import service from '@/request/request';
import DOMPurify from 'dompurify';
import { 
  initDB, 
  saveMessagesToIndexedDB, 
  loadMessagesFromIndexedDB, 
  clearAllChatHistory, 
  exportChatHistory as exportChat,
  importChatHistory as importChat
} from '@/utils/chatStorage';

// 用户信息
const userStore = useUserStore();
const userAvatar = userStore.userInfo?.avatarUrl || '';
const userId = userStore.userId || 'anonymous';

// 响应式数据
const messages = ref([]);
const inputMessage = ref('');
const messagesRef = ref(null);
const inputRef = ref(null);
const isLoading = ref(false);
const db = ref(null);

// 监听消息变化，自动保存
watch(messages, () => {
  if (db.value && messages.value.length > 0) {
    saveMessagesToIndexedDB(db.value, userId, messages.value)
      .catch(err => console.error('自动保存失败:', err));
  }
}, { deep: true });

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}/${month}/${day} ${hours}:${minutes}`;
};

// 格式化消息内容
const formatMessageContent = (content) => {
  // 先移除思考标记内容
  content = removeThinkTags(content);
  
  // 防止XSS攻击
  let sanitizedContent = DOMPurify.sanitize(content);
  
  // 处理换行符
  sanitizedContent = sanitizedContent.replace(/\n/g, '<br>');
  
  // 确保短消息不换行
  if (sanitizedContent.length < 30 && !sanitizedContent.includes('<br>')) {
    return `<span style="white-space: nowrap">${sanitizedContent}</span>`;
  }
  
  return sanitizedContent;
};

// 移除思考标记
const removeThinkTags = (content) => {
  if (!content) return '';
  // 移除所有<think>标签及其内容
  return content.replace(/<think>[\s\S]*?<\/think>/g, '')
                .replace(/<think>/g, '')
                .replace(/<\/think>/g, '');
};

// 处理Enter键
const handleEnterKey = (e) => {
  if (e.shiftKey) {
    // Shift+Enter 换行 - 不阻止默认行为，允许换行
    return;
  } else {
    // Enter 发送
    e.preventDefault(); // 仅在非Shift+Enter情况下阻止默认行为
    sendMessage();
  }
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
  }
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;
  
  // 设置加载状态
  isLoading.value = true;
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message,
    time: new Date()
  });
  
  // 清空输入框
  inputMessage.value = '';
  
  // 滚动到底部
  await scrollToBottom();
  
  // 尝试保存到IndexedDB（消息变化watch会自动触发保存，这里作为额外保障）
  if (db.value) {
    try {
      await saveMessagesToIndexedDB(db.value, userId, messages.value);
    } catch (error) {
      console.error('保存消息失败:', error);
    }
  }
  
  // 添加AI消息（带加载状态）
  const aiMessageIndex = messages.value.length;
  messages.value.push({
    role: 'assistant',
    content: '',
    time: new Date(),
    loading: true
  });
  
  try {
    // 调用实际的后端API并处理流式响应
    await service({
      url: '/deepseek/ai/chat1', // 实际的后端API路径
      method: 'POST',
      data: { message }, // 发送给后端的数据格式
      responseType: 'text', // 使用text类型来处理流式响应
      timeout: 120000, // 增加超时时间
      onDownloadProgress: (progressEvent) => {
        const responseText = progressEvent.event.currentTarget.response;
        // console.log(responseText)
        if (responseText) {
          // 解析SSE格式的响应
          const lines = responseText.split('\n');
          let accumulatedContent = '';
          
          // 处理每一行SSE数据
          for (const line of lines) {
            if (line.trim().startsWith('data: ')) {
              try {
                // 提取data:后面的JSON字符串并解析
                const jsonStr = line.trim().substring(5).trim();
                if (jsonStr && jsonStr !== '[DONE]') {
                  const jsonData = JSON.parse(jsonStr);
                  
                  // 提取content内容并移除思考标记
                  if (jsonData.choices && 
                      jsonData.choices[0] && 
                      jsonData.choices[0].delta && 
                      jsonData.choices[0].delta.content) {
                      
                      // 获取内容并移除思考标记  
                      const content = jsonData.choices[0].delta.content;
                      const filteredContent = removeThinkTags(content);
                      
                      if (filteredContent.trim()) {
                        accumulatedContent += filteredContent;
                      }
                  }
                }
              } catch (e) {
                console.error('解析SSE数据失败:', e, line);
              }
            }
          }
          
          // 更新AI消息内容
          if (accumulatedContent) {
            messages.value[aiMessageIndex].content = accumulatedContent;
            scrollToBottom();
          }
        }
      }
    });
    
    // 请求完成，移除加载状态
    messages.value[aiMessageIndex].loading = false;
    
    // 如果没有内容（很少发生，但为了安全起见）
    if (!messages.value[aiMessageIndex].content) {
      messages.value[aiMessageIndex].content = '抱歉，服务器返回了空响应，请稍后再试。';
    }
  } catch (error) {
    console.error('AI对话请求错误:', error);
    
    // 显示错误消息
    messages.value[aiMessageIndex].content = '抱歉，服务器连接失败，请检查网络连接或稍后再试。';
    messages.value[aiMessageIndex].loading = false;
    
    // 显示错误提示
    ElMessage.error('与AI对话发生错误，请稍后再试');
  } finally {
    // 无论成功或失败，都重置加载状态
    isLoading.value = false;
    await scrollToBottom();
  }
};

// 复制消息
const copyMessage = (content) => {
  // 创建一个临时textarea元素
  const textarea = document.createElement('textarea');
  // 去除HTML标签
  const plainText = content.replace(/<[^>]*>?/gm, '');
  textarea.value = plainText;
  document.body.appendChild(textarea);
  textarea.select();
  
  try {
    // 执行复制命令
    document.execCommand('copy');
    ElMessage.success('消息已复制到剪贴板');
  } catch (err) {
    ElMessage.error('复制失败');
    console.error('复制失败:', err);
  }
  
  // 移除临时元素
  document.body.removeChild(textarea);
};

// 删除消息
const deleteMessage = (index) => {
  messages.value.splice(index, 1);
  ElMessage.success('消息已删除');
};

// 组件挂载完成
onMounted(async () => {
  // 聚焦输入框
  inputRef.value?.focus();
  
  try {
    // 初始化数据库
    db.value = await initDB();
    
    // 加载历史消息
    const loadedMessages = await loadMessagesFromIndexedDB(db.value, userId);
    messages.value = loadedMessages;
    
    // 初始加载时滚动到底部
    scrollToBottom();
  } catch (error) {
    console.error('初始化数据库或加载消息失败:', error);
    ElMessage.warning('无法加载历史聊天记录');
  }
});

// 导出聊天记录
const exportChatHistory = async () => {
  if (messages.value.length === 0) {
    ElMessage.warning('没有聊天记录可导出');
    return;
  }
  
  try {
    await exportChat(messages.value, userId);
    ElMessage.success('聊天记录已导出');
  } catch (error) {
    console.error('导出聊天记录失败:', error);
    ElMessage.error('导出聊天记录失败: ' + error.message);
  }
};

// 文件输入引用
const fileInput = ref(null);

// 触发文件选择对话框
const triggerImport = () => {
  fileInput.value.click();
};

// 导入聊天记录
const importChatHistory = async (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  try {
    // 导入消息
    const importedMessages = await importChat(file);
    
    // 更新消息
    messages.value = importedMessages;
    
    // 保存到IndexedDB
    if (db.value) {
      await saveMessagesToIndexedDB(db.value, userId, messages.value);
    }
    
    ElMessage.success('聊天记录导入成功');
    await scrollToBottom();
  } catch (error) {
    console.error('导入聊天记录失败:', error);
    ElMessage.error('导入失败: ' + (error.message || '无效的文件格式'));
  } finally {
    // 重置文件输入
    event.target.value = '';
  }
};

// 清除聊天记录
const handleClearAllChatHistory = async () => {
  try {
    await clearAllChatHistory(db.value);
    messages.value = [];
    ElMessage.success('聊天记录已清除');
  } catch (error) {
    console.error('清除聊天记录失败:', error);
    ElMessage.error('清除聊天记录失败: ' + error.message);
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  background-color: #f9f9f9;
  border-radius: 12px;
  overflow: hidden;
}

/* 消息区域样式 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
  background-color: #f9f9f9;
}

/* 自定义滚动条 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-track {
  background-color: transparent;
}

/* 消息项样式 */
.message-item {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
  width: 100%;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.avatar {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.ai-message .avatar {
  margin: 0 10px 0 0;
}

.user-message .avatar {
  margin: 0 0 0 12px;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.user-message .message-content {
  align-items: flex-end;
}

.ai-message .message-content {
  align-items: flex-start;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  width: fit-content;
  max-width: 100%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.user-message .message-bubble {
  background-color: #8c3eff;
  color: white;
  border-radius: 20px;
}

.ai-message .message-bubble {
  background-color: #f0f0f0;
  color: #333;
  border-radius: 20px;
}

.message-bubble p {
  margin: 0;
  line-height: 1.5;
  word-break: break-word;
  white-space: pre-wrap;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.message-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.message-item:hover .message-actions {
  opacity: 1;
}

.message-actions .el-icon {
  cursor: pointer;
  font-size: 16px;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
}

.message-actions .el-icon:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: #409EFF;
}

/* 输入区域样式 */
.chat-input {
  display: flex;
  padding: 16px;
  background-color: white;
  border-top: 1px solid #eee;
  position: relative;
}

.chat-input :deep(.el-textarea__inner) {
  resize: none;
  max-height: 120px;
  padding-right: 60px; /* 为按钮留出空间 */
  border-radius: 30px;
  transition: all 0.2s;
  line-height: 1.5;
  padding: 12px 60px 12px 16px;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.chat-input :deep(.el-textarea__inner:focus) {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  border-color: #dcdfe6;
}

.chat-input :deep(.el-textarea__inner:disabled) {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

.send-button-wrapper {
  position: absolute;
  right: 16px; /* a调整右侧距离 */
  bottom: 0;
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.send-button {
  width: 44px;
  height: 44px;
  background-color: #f2f3f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  color: #606266;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.send-button:hover {
  background-color: #e6e8eb;
  transform: translateY(-2px);
}

.send-button.disabled {
  background-color: #f2f3f5;
  color: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
  opacity: 0.7;
}

.send-button .el-icon {
  font-size: 20px;
  transform: rotate(45deg); /* 旋转图标使其指向右上方 */
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #999;
  border-radius: 50%;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 100% {
    transform: scale(1);
    opacity: 0.3;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
}

/* 添加聊天操作区域样式 */
.chat-actions {
  padding: 10px;
  display: flex;
  justify-content: center;
  gap: 10px;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

.chat-actions .el-button {
  font-size: 12px;
}
</style>
